<template>
    <div class="menu-manage-container">
        <!-- 搜索区域 -->
        <div class="search-area">
            <el-input v-model="searchMenuName" placeholder="请输入菜单名称" style="width: 200px;"></el-input>
            <el-select v-model="searchIsValid" placeholder="请选择是否有效" style="width: 200px;">
                <el-option label="有效" value="1" />
                <el-option label="无效" value="0" />
            </el-select>
            <el-button @click="searchMenus" type="primary" icon="el-icon-search" style="width: 10%;">搜索</el-button>
            <el-button @click="resetSearch" type="info" icon="el-icon-delete" style="width: 10%;">重置</el-button>
        </div>

        <!-- 新增用户按钮区域 -->
        <div class="add-menu-area">
            <el-button @click="openDialog('add')" type="success" icon="el-icon-plus"
                style="width: 10%;">新增菜单</el-button>
        </div>

        <!-- 菜单列表区域 -->
        <el-table :data="menuList" stripe border>
            <el-table-column prop="menuName" label="菜单名称" width="150"></el-table-column>
            <el-table-column prop="menuType" label="菜单类型" width="150" :formatter="formatMenuType"></el-table-column>
            <el-table-column prop="parentMenuName" label="父菜单名称" width="150"></el-table-column>
            <el-table-column prop="routerPath" label="路由地址" width="150"></el-table-column>
            <el-table-column prop="component" label="组件路径" width="150"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button @click="openDialog('detail', scope.row)" type="success" icon="el-icon-view"
                        style="width: 100px; text-align: center;">查看详情</el-button>
                    <el-button @click="openDialog('edit', scope.row)" type="warning" icon="el-icon-edit"
                        style="width: 100px; text-align: center;">修改菜单</el-button>
                    <el-button @click="deleteMenu(scope.row.menuId)" type="danger" icon="el-icon-delete"
                        style="width: 100px; text-align: center;">删除菜单</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>

        <!-- 新增/修改/详情弹窗 -->
        <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" custom-class="add-menu-dialog"
            :show-close="false">
            <el-form :model="formMenu" ref="menuForm" label-width="120px" :disabled="dialogMode === 'detail'">
                <el-form-item label="菜单名称">
                    <el-input v-model="formMenu.menuName"></el-input>
                </el-form-item>
                <el-form-item label="菜单类型">
                    <el-select v-model="formMenu.menuType" placeholder="请选择菜单类型" @change="handleMenuTypeChange">
                        <el-option label="目录" value="1"></el-option>
                        <el-option label="菜单" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="父菜单" v-if="formMenu.menuType === '2'">
                    <el-select v-model="formMenu.parentId" placeholder="请选择父菜单">
                        <el-option label="无" value="0"></el-option>
                        <el-option v-for="menu in parentMenus" :key="menu.menuId" :label="menu.menuName"
                            :value="menu.menuId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="路由地址">
                    <el-input v-model="formMenu.routerPath"></el-input>
                </el-form-item>
                <el-form-item label="组件路径">
                    <el-input v-model="formMenu.component"></el-input>
                </el-form-item>
                <el-form-item label="菜单图标">
                    <el-input v-model="formMenu.icon"></el-input>
                </el-form-item>
                <el-form-item label="是否有效">
                    <el-select v-model="formMenu.isValid">
                        <el-option label="是" value="1" />
                        <el-option label="否" value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="绑定角色" v-if="dialogMode === 'detail'">
                    <el-input 
                        v-model="boundRoleNames" 
                        type="textarea" 
                        :rows="3" 
                        placeholder="暂无绑定角色" 
                        readonly
                    ></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button v-if="dialogMode !== 'detail'" @click="submitMenu" type="primary">确定</el-button>
                    <el-button @click="dialogVisible = false" type="danger">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    name: 'MenuList',
    data() {
        return {
            // 搜索参数
            searchMenuName: '',
            searchIsValid: '1',
            // 菜单列表
            menuList: [],
            parentMenus: [], // 新增：存储顶级菜单
            // 分页参数
            currentPage: 1,
            pageSize: 10,
            total: 0,
            // 弹窗相关
            dialogVisible: false,
            dialogMode: '',
            dialogTitle: '',
            formMenu: {
                menuId: null,
                menuName: '',
                menuType: '1',
                parentId: 0,
                routerPath: '',
                component: '',
                icon: '',
                isValid: '1'
            },
            // 详情页面展示，绑定的角色名称（逗号分隔）
            boundRoleNames: ''
        };
    },
    methods: {
        // 获取菜单列表
        searchMenus() {
            axios.get('http://localhost:8080/shopping/menu/list', {
                params: {
                    menuName: this.searchMenuName,
                    isValid: this.searchIsValid,
                    currentPage: this.currentPage,
                    pageSize: this.pageSize
                }
            }).then(response => {
                this.menuList = response.data.data.records;
                this.total = response.data.total;
                this.parentMenus = this.menuList.filter(menu => menu.menuType === 1) // 只展示目录
            }).catch(error => {
                console.error('搜索菜单失败:', error);
            });
        },
        // 重置搜索
        resetSearch() {
            this.searchMenuName = '';
            this.searchIsValid = '1';
            this.currentPage = 1;
            this.searchMenus();
        },

        // 打开弹窗
        openDialog(mode, menu = null) {
            this.dialogMode = mode;
            this.dialogVisible = true;
            if (mode === 'add') {
                this.dialogTitle = '新增菜单';
                this.formMenu = {
                    menuId: null,
                    menuName: '',
                    menuType: '1',
                    parentId: '0',
                    routerPath: '',
                    component: '',
                    icon: '',
                    isValid: '1'
                };
            } else {
                axios.get('http://localhost:8080/shopping/menu/detail', {
                    params: {menuId: menu.menuId}
                }).then(response => {
                    const menuDb = response.data.data;
                    this.boundRoleNames = menuDb.roles;
                    this.dialogTitle = mode === 'edit' ? '修改菜单' : '菜单详情';
                    this.formMenu = {
                        menuId: menuDb.menuId,
                        menuName: menuDb.menuName,
                        menuType: menuDb.menuType.toString(),
                        parentId: menuDb.parentId,
                        routerPath: menuDb.routerPath,
                        component: menuDb.component,
                        icon: menuDb.icon,
                        isValid: menuDb.isValid.toString()
                    }
                })
            }
        },
        // 提交新增/修改菜单
        submitMenu() {
            const payload = {
                ...this.formMenu,
                menuType: parseInt(this.formMenu.menuType),
                isValid: parseInt(this.formMenu.isValid),
                parentId: this.formMenu.menuType === '1' ? 0 : parseInt(this.formMenu.parentId) // 目录类型强制无父菜单
            };
            const method = this.dialogMode === 'edit' ? 'put' : 'post';
            const url = this.dialogMode === 'edit' ? 'http://localhost:8080/shopping/menu/edit' : 'http://localhost:8080/shopping/menu/add';
            axios[method](url, payload).then(response => {
                if (response.data.code === 200) {
                    this.$message.success(`${this.dialogMode === 'edit' ? '修改' : '新增'}菜单成功`);
                    this.dialogVisible = false;
                    this.searchMenus();
                } else {
                    this.$message.error(`${this.dialogMode === 'edit' ? '修改' : '新增'}菜单失败: ${response.data.message}`);
                }
            }).catch(error => {
                console.error(`${this.dialogMode === 'edit' ? '修改' : '新增'}菜单失败:`, error);
                this.$message.error(`${this.dialogMode === 'edit' ? '修改' : '新增'}菜单失败，请检查网络`);
            });
        },

        // 删除菜单
        deleteMenu(menuId) {
            this.$confirm('确定要删除该菜单吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios.delete('http://localhost:8080/shopping/menu/del', {
                    params: { menuId }
                }).then(response => {
                    if (response.data.code === 200) {
                        this.$message.success('删除菜单成功');
                        this.searchMenus();
                    } else {
                        this.$message.error('删除菜单失败:' + response.data.message);
                    }
                }).catch(error => {
                    console.error('删除菜单失败:', error);
                    this.$message.error('删除菜单失败，请检查网络');
                });
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },

        // 格式化菜单类型
        formatMenuType(row, column) {
            return column.menuType === '1' ? '目录' : '菜单';
        },
        // 处理菜单类型变化
        handleMenuTypeChange(value) {
            if (value === '1') { // 选择目录类型
                this.formMenu.parentId = '0'; // 自动设置为无父菜单
            }
        },

        // 每页数量变化
        handleSizeChange(newSize) {
            this.pageSize = newSize;
            this.searchMenus();
        },
        // 当前页码变化
        handleCurrentChange(newPage) {
            this.currentPage = newPage;
            this.searchMenus();
        }
    },
    mounted() {
        this.searchMenus();
    }
};
</script>

<style scoped>
.menu-manage-container {
    padding: 20px;
}

.search-area {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.search-area .el-input {
    margin-right: 10px;
}

.search-area .el-select {
    margin-right: 10px;
}

.search-area .el-button {
    margin-right: 10px;
}

.el-button {
    height: 40px;
    margin-top: -12px;
}

.add-menu-area {
    margin-bottom: 20px;
}

.el-table {
    margin-bottom: 20px;
}

.add-menu-dialog {
    width: 500px;

    .el-dialog__header {
        background-color: #f0f9eb;
        border-bottom: 1px solid #e5e5e5;
        padding: 15px;
    }

    .el-dialog__title {
        color: #67c23a;
        font-size: 18px;
    }

    .el-dialog__body {
        padding: 20px;
    }

    .el-dialog__footer {
        border-top: 1px solid #e5e5e5;
        padding: 15px;
        text-align: right;
    }
}
</style>